<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/11/4
 * Time: 14:10
 */

namespace Common\Api;


use Admin\Api\OrdersPaycodeApi;
use Admin\Api\UidMgroupApi;
use Common\ConstVar\BoyeActionConstModel;
use Shop\Api\MemberConfigApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductAttrApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\WalletApi;

class PayOrderApi {
    //支付成功时
    const SUCCESS = "Common/PayOrder/success";

    public function success($out_trade_nos,$pay_type){

        addLog("PayOrder/success",$out_trade_nos,$out_trade_nos,"1.PayOrderApi SUCCESS!");
        $p_pos = strpos($out_trade_nos,"P");
        $pay_id = substr($out_trade_nos,$p_pos+1,strlen($out_trade_nos)-$p_pos);

        $map=array(
            'id'=>$pay_id
        );
        $result=apiCall(OrdersPaycodeApi::GET_INFO,array($map));
        $u_pos = strpos($out_trade_nos,"U");
        $uid = substr($out_trade_nos,$u_pos+1,$p_pos-$u_pos-1);

        addLog("GAlipay/notify_url",$uid.'_'.$pay_id,$result,"获取支付编号对应的订单编号"."3.支付成功异步通知!");
        //2. 支付成功后更新订单状态
        if($result['status'] && is_array($result['info'])){

            $orderCodeArray=explode(';',$result['info']['order_content']);

            foreach($orderCodeArray as $order_code){
                if(empty($order_code)){
                    continue;
                }

                addLog("GAlipay/notify_url",$uid,$out_trade_nos,$order_code."修改订单支付状态"."4.支付成功异步通知!");
                $result = apiCall(OrderStatusApi::PAY_ORDER,array($out_trade_nos,$order_code,$uid,$pay_type));

                if(!$result['status']){
                    addLog("GAlipay/notify_url",$result['info'],$result,"修改订单支付状态"."4.1 修改订单为已支付出错!");
                    continue;
                }

                addLog("GAlipay/notify_url",$result['info'],$result,"4.2 支付成功后进入程序处理，比如返佣，用户经验值纪录!");
                //TODO:
                // 1. 计算返佣
                // 2. 统计成交笔数,对用户级别进行升级
                // 3. 发送通知给用户？
                // 4. 减库存？
                // 5.

                $result = apiCall(OrdersApi::GET_INFO,array(array('order_code'=>$order_code)));
                if(!$result['status']){
                    LogRecord($result['info'],__FILE__.__LINE__);
                    addLog("GAlipay/notify_url",$uid,$result,"订单信息获取"."5. 订单信息获取失败!");
                    return;
                }
                $order_info = $result['info'];
                if(is_null($order_info)){
                    addLog("GAlipay/notify_url",$uid,$result,"订单信息获取"."6. 订单信息获取失败!");
                    continue;
                }

                // 1. 用户经验+1
                action_log(BoyeActionConstModel::PAY_SUCCESS,"member_config",$uid,$uid);

                addLog("GAlipay/notify_url",$uid,$result,"订单信息获取"."7.用户经验+1!");

                // 2. 更新用户组
                $this->updateMemberGroup($order_info,$uid);
                addLog("GAlipay/notify_url",$uid,$result,"更新用户组"."8. 更新用户组!");

                // 3. 返佣的计算
                $this->calCommission($order_info,$uid);
                addLog("GAlipay/notify_url",$uid,$result,"用户返佣"."9. 用户返佣!");

                // 4. 增加商品销量,并减少库存
                $this->addProductSalesAndMinusQuantity($order_code);
                addLog("GAlipay/notify_url",$uid,$result,"增加商品销量!");

                //5. 自动确认订单
                $this->autoConfirmOrder($order_code,$uid);
                //6. 插入快递信息

            }
            return 0;
        }

        return -2;
    }

    private function autoConfirmOrder($order_code,$uid){
        $result = apiCall(OrderStatusApi::CONFIRM_ORDER,array($order_code));
        if(!$result['status']){
            addLog("GAlipay/autoConfirmOrder",$order_code,$result,"自动确认订单失败!");
            return;
        }

        $entity = array(
            'expresscode'=>'ems',
            'expressname'=>'ems快递',
            'expressno'=>'',
            'note'=>'尚未发货',
            'order_code'=>$order_code,
            'uid'=>$uid,
        );

        $result = apiCall(OrdersExpressApi::ADD, array($entity));

        if(!$result['status']){
            addLog("GAlipay/autoConfirmOrder",$order_code,$result,"自动生成快递信息失败!");
            return;
        }
    }

    private function addProductSalesAndMinusQuantity($order_code){

        $result = apiCall(OrdersItemApi::QUERY_NO_PAGING,array(array('order_code'=>$order_code)));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
            return;
        }

        foreach($result['info'] as $item){

            $p_id = $item['p_id'];
            $sku_id = trim($item['sku_id']);
            $quantity = $item['count'];

            addLog("PayOrderApi",$quantity,$p_id,"[调试] 销量增加",true);
            $result = apiCall(ProductAttrApi::SET_INC,array(array('pid'=>$p_id),"total_sales",$quantity));
            if(!$result['status']){
                LogRecord($result['info'],__FILE__.__LINE__);
                return;
            }
            if(empty($sku_id)){
                $result = apiCall(ProductApi::SET_DEC,array(array('id'=>$p_id),"quantity",$quantity));
            }else{
                $result = apiCall(ProductSkuApi::SET_DEC,array(array('sku_id'=>$sku_id,'product_id'=>$p_id),"quantity",$quantity));
            }

            if(!$result['status']){
                LogRecord($result['info'],__FILE__.__LINE__);
                return;
            }


        }

    }


    /**
     * 计算返佣金额
     * @param $order_info
     * @param $uid
     */
    private function calCommission($order_info,$uid){
        //不含税
        $goodsAmount = floatval($order_info['goods_amount']);
        $discountMoney = floatval($order_info['discount_money']);
        $brokerageRatio = $order_info['brokerage_ratio'];
        addLog("PayOrderApi/calCommission",$goodsAmount,$order_info,"[调试]支付成功后!",true);

        $commission_price = round($brokerageRatio * ($goodsAmount - $discountMoney),2);
        $idcode = $order_info['idcode'];
        addLog("PayOrderApi/calCommission",$idcode,$order_info,"[调试] 计算返佣时获取到的IDCODE!",true);

        if(empty($idcode)){
           return ;
        }

        $result = apiCall(MemberConfigApi::GET_INFO,array(array('idcode'=>$idcode)));

        addLog("PayOrderApi/calCommission",$idcode,$result,"[调试] 计算返佣时获取到的Member_config!",true);

        if($result['status'] && is_array($result['info'])){
            //返佣的uid
            $uid = $result['info']['uid'];
            addLog("PayOrderApi/calCommission",C("DATATREE"),getDatatree('COMMISSION_ORDER_PAID'),"[调试] 计算返佣时的金额!",true);
            $result = apiCall(WalletApi::PLUS,array($uid,$commission_price,getDatatree('COMMISSION_ORDER_PAID'),"订单".$order_info['order_code']."返佣".$commission_price."元"));
            if(!$result['status']){
                LogRecord("增加返佣金额失败!",__FILE__.__LINE__);
            }

            addLog("PayOrderApi/calCommission",$result,$uid,"[调试] 增加返佣金额时的结果!",true);


        }else{
            LogRecord("计算返佣时获取返佣对象的用户信息失败!",__FILE__.__LINE__);
        }
    }

    private function updateMemberGroup($order_info,$uid){

        $store_id = $order_info['storeid'];

        $result = apiCall(UidMgroupApi::UPDATE_GROUP,array($uid,$store_id));
        if($result['status']){
            //1. 成功升级
            action_log(BoyeActionConstModel::M_GROUP_LEVEL_UP,"member_config",$uid,$uid);
        }

    }
}